package com.zhouyer.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zhouyer.io.Resources;
import com.zhouyer.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * XML配置够构建类
 */
public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        configuration = new Configuration();
    }

    /**
     * 解析输入字节流中的xml内容，并封装到Configuration中
     *
     * @param inputStream
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);
        // 获取跟元素<configuration>
        Element rootElement = document.getRootElement();
        // 获取所有的<property>元素
        List<Element> list = rootElement.selectNodes("//property");

        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        // 使用连接池穿件DataSource
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("user"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(comboPooledDataSource);

        // mapper.xml解析 ，可能存在多个mapper.xml
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
//            获取mapper的路径->获取该路径的字节输入流->通过dom4j解析内容
            String mapperPath = element.attributeValue("resource");
            InputStream inputStream1 = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(inputStream1);
        }
        return configuration;
    }
}
